"""
动态项目类型管理器
从配置文件和用户数据中动态获取项目类型，支持用户自定义
"""

import json
import os
from typing import Dict, List, Any, Optional
from pathlib import Path

class DynamicProjectTypeManager:
    """动态项目类型管理器"""
    
    def __init__(self, config_path: Optional[str] = None):
        self.config_path = config_path or os.path.join(
            os.path.dirname(__file__), 'templates', 'project_types.json'
        )
        self.project_types = {}
        self.ui_frameworks = {}
        self.user_defined_types = {}
        self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        try:
            if os.path.exists(self.config_path):
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.project_types = config.get('project_types', {})
                    self.ui_frameworks = config.get('ui_frameworks', {})
                print(f"✅ 加载项目类型配置: {len(self.project_types)} 个预设类型")
            else:
                print(f"⚠️ 配置文件不存在: {self.config_path}")
                self._create_default_config()
        except Exception as e:
            print(f"❌ 加载配置文件失败: {str(e)}")
            self._create_default_config()
    
    def _create_default_config(self):
        """创建默认配置"""
        self.project_types = {
            "custom": {
                "name": "自定义项目",
                "description": "用户自定义的项目类型",
                "common_modules": [],
                "suggested_icons": ["folder", "settings", "home"],
                "typical_routes": ["/"]
            }
        }
        self.ui_frameworks = {
            "vue": {"name": "Vue.js", "router_patterns": ["vue-router"]},
            "react": {"name": "React", "router_patterns": ["react-router"]}
        }
    
    def analyze_project_from_files(self, package_json_path: Optional[str] = None, 
                                 router_config_path: Optional[str] = None) -> Dict[str, Any]:
        """从项目文件中分析项目类型"""
        analysis = {
            "detected_type": None,
            "confidence": 0.0,
            "ui_framework": None,
            "dependencies": [],
            "custom_modules": [],
            "suggested_type": None
        }
        
        if package_json_path and os.path.exists(package_json_path):
            analysis.update(self._analyze_package_json(package_json_path))
        
        if router_config_path and os.path.exists(router_config_path):
            analysis.update(self._analyze_router_config(router_config_path))
        
        # 根据分析结果推荐项目类型
        analysis["suggested_type"] = self._suggest_project_type(analysis)
        
        return analysis
    
    def _analyze_package_json(self, package_json_path: str) -> Dict[str, Any]:
        """分析package.json文件"""
        analysis = {"dependencies": [], "ui_framework": None}
        
        try:
            with open(package_json_path, 'r', encoding='utf-8') as f:
                package_data = json.load(f)
            
            # 提取所有依赖
            dependencies = {}
            dependencies.update(package_data.get('dependencies', {}))
            dependencies.update(package_data.get('devDependencies', {}))
            analysis["dependencies"] = list(dependencies.keys())
            
            # 检测UI框架
            for framework, config in self.ui_frameworks.items():
                for pattern in config.get('router_patterns', []):
                    if any(pattern in dep for dep in dependencies.keys()):
                        analysis["ui_framework"] = framework
                        break
                if analysis["ui_framework"]:
                    break
            
            # 检测项目类型线索
            analysis["type_hints"] = self._extract_type_hints(dependencies, package_data)
            
        except Exception as e:
            print(f"❌ 分析package.json失败: {str(e)}")
        
        return analysis
    
    def _analyze_router_config(self, router_config_path: str) -> Dict[str, Any]:
        """分析路由配置文件"""
        analysis = {"routes": [], "route_patterns": []}
        
        try:
            with open(router_config_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 简单的路由提取（可以根据实际需要改进）
            import re
            
            # Vue Router 模式
            vue_routes = re.findall(r"path:\s*['\"]([^'\"]+)['\"]", content)
            if vue_routes:
                analysis["routes"].extend(vue_routes)
                analysis["route_patterns"].append("vue-router")
            
            # React Router 模式
            react_routes = re.findall(r"<Route\s+path=['\"]([^'\"]+)['\"]", content)
            if react_routes:
                analysis["routes"].extend(react_routes)
                analysis["route_patterns"].append("react-router")
            
        except Exception as e:
            print(f"❌ 分析路由配置失败: {str(e)}")
        
        return analysis
    
    def _extract_type_hints(self, dependencies: Dict[str, str], package_data: Dict[str, Any]) -> List[str]:
        """从依赖和包信息中提取项目类型线索"""
        hints = []
        
        # 检查关键词
        dep_string = " ".join(dependencies.keys()).lower()
        package_name = package_data.get('name', '').lower()
        description = package_data.get('description', '').lower()
        
        all_text = f"{dep_string} {package_name} {description}"
        
        # 定义关键词映射 - 简化为两类
        keyword_mapping = {
            "admin": "web_app",
            "management": "web_app", 
            "dashboard": "web_app",
            "chart": "web_app",
            "analytics": "web_app",
            "ecommerce": "web_app",
            "shop": "web_app",
            "commerce": "web_app",
            "cms": "web_app",
            "content": "web_app",
            "blog": "web_app",
            "business": "web_app",
            "crm": "web_app",
            "erp": "web_app",
            "mobile": "mobile_app",
            "app": "mobile_app",
            "miniprogram": "mobile_app",
            "wechat": "mobile_app",
            "uni-app": "mobile_app"
        }
        
        for keyword, project_type in keyword_mapping.items():
            if keyword in all_text:
                hints.append(project_type)
        
        return list(set(hints))  # 去重
    
    def _suggest_project_type(self, analysis: Dict[str, Any]) -> Optional[str]:
        """根据分析结果建议项目类型"""
        hints = analysis.get("type_hints", [])
        routes = analysis.get("routes", [])
        
        # 基于提示词的建议
        if hints:
            return hints[0]  # 返回第一个匹配的类型
        
        # 基于路由的建议 - 简化为两类
        route_keywords = {
            "web_app": ["user", "role", "permission", "setting", "dashboard", "chart", "analytics", "report", "product", "order", "cart", "payment", "post", "article", "content", "category", "customer", "business", "project", "task"],
            "mobile_app": ["home", "profile", "notification", "settings", "scan", "location"]
        }
        
        for project_type, keywords in route_keywords.items():
            route_text = " ".join(routes).lower()
            if any(keyword in route_text for keyword in keywords):
                return project_type
        
        return "web_app"  # 默认为Web应用
    
    def get_project_type_info(self, type_key: str) -> Dict[str, Any]:
        """获取项目类型信息"""
        if type_key in self.project_types:
            return self.project_types[type_key]
        elif type_key in self.user_defined_types:
            return self.user_defined_types[type_key]
        else:
            return self.project_types.get("custom", {})
    
    def add_custom_project_type(self, type_key: str, type_info: Dict[str, Any]):
        """添加自定义项目类型"""
        self.user_defined_types[type_key] = type_info
        print(f"✅ 添加自定义项目类型: {type_key}")
    
    def get_available_types(self) -> Dict[str, str]:
        """获取所有可用的项目类型"""
        all_types = {}
        
        # 预设类型
        for key, info in self.project_types.items():
            all_types[key] = info.get("name", key)
        
        # 用户定义类型
        for key, info in self.user_defined_types.items():
            all_types[key] = info.get("name", key)
        
        return all_types
    
    def get_ui_framework_info(self, framework_key: str) -> Dict[str, Any]:
        """获取UI框架信息"""
        return self.ui_frameworks.get(framework_key, {})
    
    def save_user_types(self, file_path: Optional[str] = None):
        """保存用户自定义类型到文件"""
        if not self.user_defined_types:
            return
        
        save_path = file_path or os.path.join(
            os.path.dirname(self.config_path), 'user_defined_types.json'
        )
        
        try:
            with open(save_path, 'w', encoding='utf-8') as f:
                json.dump(self.user_defined_types, f, ensure_ascii=False, indent=2)
            print(f"✅ 用户自定义类型已保存到: {save_path}")
        except Exception as e:
            print(f"❌ 保存用户自定义类型失败: {str(e)}")
    
    def load_user_types(self, file_path: Optional[str] = None):
        """从文件加载用户自定义类型"""
        load_path = file_path or os.path.join(
            os.path.dirname(self.config_path), 'user_defined_types.json'
        )
        
        if os.path.exists(load_path):
            try:
                with open(load_path, 'r', encoding='utf-8') as f:
                    self.user_defined_types = json.load(f)
                print(f"✅ 加载用户自定义类型: {len(self.user_defined_types)} 个")
            except Exception as e:
                print(f"❌ 加载用户自定义类型失败: {str(e)}")
